<?php

namespace App\Http\Middleware;

use App\Models\Admin\AdminUsers as Users;
use App\Models\Tokens;
use Closure;

class AdminLoginMiddleware
{

    public function __construct()
    {
    }

    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = '';
//      优先使用header
        if ($request->hasHeader('Authorization')) {
            $token = $request->header('Authorization');
        } else if ($request->has('Authorization')) {
            $token = rawurldecode($request->get('Authorization'));
        }
        if (empty($token)) {
            return response(array(
                'code' => ERROR_NONE_LOGIN_CODE,
                'msg' => '缺少用户信息',
                'data' => null,
            ));
        };

        try {
            $token = trim(str_replace('Bearer ', '', $token));
            $isValid = Tokens::where(array('token' => $token))->first();
            if (!$isValid) {
                return response(array(
                    'code' => ERROR_NONE_LOGIN_CODE,
                    'msg' => '请重新登录',
                    'data' => null,
                ));
            }
            // 登录超时
            if (empty($isValid->updated_at) || ((time() - strtotime($isValid->updated_at)) > (2 * 60 * 60))) {
                return response(array(
                    'code' => ERROR_NONE_LOGIN_CODE,
                    'msg' => '已超时,请重新登录',
                    'data' => null,
                ));
            }
            $isValid = json_decode(json_encode($isValid), true);
            $userId = $isValid['user_id'];
            $user = Users::select(['id', 'nick_name', 'user_name', 'shop_id', 'dept_id', 'supplier', 'supervisor_id', 'role_id', 'agent_id'])->find($userId);
            // var_dump($user->user_name);
//            登陆者有操作的时间,表示登陆着
//            if (!empty($user)) {
//                Users::where(['id' => $user['id']])->update(array('update_time' => date('Y-m-d H:i:s')));
//            }

            Tokens::where(array('token' => $token))->update(array('user_name' => $user->user_name, 'updated_at' => date('Y-m-d H:i:s')));

            $request->merge(['user' => $user]);
        } catch (\Exception $e) {
            return response(array(
                'code' => ERROR_NONE_LOGIN_CODE,
                'msg' => '未找到用户信息',
                'data' => null,
            ));
        }

        return $next($request);
    }
}
